import { useEffect } from 'react';
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import 'react-native-reanimated';

import { useColorScheme } from '@/hooks/useColorScheme';
import NotificationService from '../services/notification';
import GeofenceService from '../services/geofence';

export default function RootLayout() {
  const colorScheme = useColorScheme();
  const [fontsLoaded] = useFonts({
  });

  useEffect(() => {
    // 初始化通知和地理围栏服务
    const initServices = async () => {
      // 请求通知权限并初始化
      const hasNotificationPermission = await NotificationService.requestPermissions();
      if (hasNotificationPermission) {
        console.log('通知服务已初始化');
      }

      // 请求位置权限并初始化地理围栏
      const hasLocationPermission = await GeofenceService.requestPermissions();
      if (hasLocationPermission) {
        await GeofenceService.initializeGeofences();
        console.log('地理围栏服务已初始化');
      }
    };

    initServices();

    // 组件卸载时清理
    return () => {
      GeofenceService.stopGeofencing();
    };
  }, []);

  const [loaded] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
  });

  if (!fontsLoaded) {
    // Async font loading only occurs in development.
    return null;
  }

  return (
    <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
      <Stack>
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="+not-found" />
      </Stack>
      <StatusBar style="auto" />
    </ThemeProvider>
  );
}
